package com.imooc.spark.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.*;

public class new_Kafka_ConsumerApp {

    public static void main(String[] args) {

        //1 创建消费者配置信息,相当于配置文件
        Properties properties = new Properties();

        //2 编辑配置信息   连接集群    开启自动提交    自动提交的延迟    KV的反序列化   消费者组
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.19.158:9092");
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,true);
        //提交Offect，默认是1000毫秒=1秒
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,"1000");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"testgroup");


        //创建消费者
        KafkaConsumer<String,String> kafkaConsumer = new KafkaConsumer<String,String>(properties);
        //定义主题,参数是一个集合这里就算写错了一个主题，也不影响其他主题，这里写一个就行.
        //kafkaConsumer.subscribe(Arrays.asList("test","first"));      优化集合:   alt + enter
        kafkaConsumer.subscribe(Collections.singletonList("test"));

        while(true){
            //拉取数据 , 参数是long :轮询间隔
            ConsumerRecords<String, String> consumerRecords =  kafkaConsumer.poll(1000);

            for (ConsumerRecord<String, String> consumerRecord:consumerRecords) {
                System.out.println(consumerRecord.key()+"--"+consumerRecord.value());
            }
        }

    }
}
